package com.jackson.payparams.utils;

/*
 * Author: JacksonCoder
 * FileName: GenerateAPISignature
 * Version: 1.0.0
 * Date: 2025/7/14
 */

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Base64;

public class GenerateAPISignature {
    public static void main(String[] args) throws Exception {
        String method = "POST";
        String url = "/direct-debit/core/v1/debit/payment-host-to-host";
        String token = "MfZRPyHdZZNbXgtbx8x57btrYxGCYxN4";  // 32
        String requestTimestamp = "2025-01-16T17:30:56+07:00";
        String clientSecret = "CKSandbox-98daa36a-35c8-4481-9e67-25fbd4c3e10a";

        // JSON body
        String body = "{\"additionalInfo\":{\"channel\":\"EMONEY_DANA_SNAP\"},\"amount\":{\"currency\":\"IDR\",\"value\":\"100.00\"},\"partnerReferenceNo\":\"3c1b6eadb87545f8865d5489704f0c44\",\"urlParams\":[{\"type\":\"NOTIFICATION\",\"url\":\"https://payment.ayolinx.id/callback/pay/notify\"},{\"type\":\"PAY_RETURN\",\"url\":\"https://payment.ayolinx.id\"}],\"validUpTo\":\"2025-01-16T17:30:56+07:00\"}";

        // Hash the body using SHA256
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        byte[] hashedBodyBytes = digest.digest(body.getBytes(StandardCharsets.UTF_8));
        String hashedBodyHex = bytesToHex(hashedBodyBytes);

        // Prepare the data
        String data = method + ":" + url + ":" + token + ":" + hashedBodyHex + ":" + requestTimestamp;

        // Create HMAC-SHA512 signature
        Mac mac = Mac.getInstance("HmacSHA512");
        SecretKeySpec secretKeySpec = new SecretKeySpec(clientSecret.getBytes(StandardCharsets.UTF_8), "HmacSHA512");
        mac.init(secretKeySpec);
        byte[] hmacBytes = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
        String signature = Base64.getEncoder().encodeToString(hmacBytes);

        System.out.println("Signature: " + signature);
    }


    // Helper method to convert byte array to hex string
    private static String bytesToHex(byte[] bytes) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) hexString.append('0');
            hexString.append(hex);
        }
        return hexString.toString();
    }
}
